{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "@tf.function\n",
    "def printbar():\n",
    "    ts = tf.timestamp()\n",
    "    today_ts = ts%(24*60*60)\n",
    "\n",
    "    hour = tf.cast(today_ts//3600+8,tf.int32)%tf.constant(24)\n",
    "    minite = tf.cast((today_ts%3600)//60,tf.int32)\n",
    "    second = tf.cast(tf.floor(today_ts%60),tf.int32)\n",
    "\n",
    "    def timeformat(m):\n",
    "        if tf.strings.length(tf.strings.format(\"{}\",m))==1:\n",
    "            return(tf.strings.format(\"0{}\",m))\n",
    "        else:\n",
    "            return(tf.strings.format(\"{}\",m))\n",
    "\n",
    "    timestring = tf.strings.join([timeformat(hour),timeformat(minite),\n",
    "                timeformat(second)],separator = \":\")\n",
    "    tf.print(\"==========\"*8,end = \"\")\n",
    "    tf.print(timestring)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================================================================23:39:26\r\n",
      "Step =  100\r\n",
      "x =  0.867380381\r\n",
      "\r\n",
      "================================================================================23:39:26\r\n",
      "Step =  200\r\n",
      "x =  0.98241204\r\n",
      "\r\n",
      "================================================================================23:39:26\r\n",
      "Step =  300\r\n",
      "x =  0.997667611\r\n",
      "\r\n",
      "================================================================================23:39:26\r\n",
      "Step =  400\r\n",
      "x =  0.999690711\r\n",
      "\r\n",
      "================================================================================23:39:26\r\n",
      "Step =  500\r\n",
      "x =  0.999959\r\n",
      "\r\n",
      "================================================================================23:39:26\r\n",
      "Step =  600\r\n",
      "x =  0.999994516\r\n",
      "\r\n",
      "y =  0\r\n",
      "x =  0.999995232\r\n"
     ]
    }
   ],
   "source": [
    "# 求f(x) = a*x**2 + b*x + c的最小值\n",
    "x = tf.Variable(0.0,name='x',dtype=tf.float32)\n",
    "optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)\n",
    "\n",
    "@tf.function\n",
    "def minimizef():\n",
    "    a = tf.constant(1.0)\n",
    "    b = tf.constant(-2.0)\n",
    "    c = tf.constant(1.0)\n",
    "    while tf.constant(True):\n",
    "        with tf.GradientTape() as tape:\n",
    "            y = a * tf.pow(x,2) + b *x + c\n",
    "        dy_dx = tape.gradient(y,x)\n",
    "        optimizer.apply_gradients(grads_and_vars=[(dy_dx,x)])\n",
    "\n",
    "        #迭代终止条件\n",
    "        if tf.abs(dy_dx)<tf.constant(0.00001):\n",
    "            break\n",
    "\n",
    "        if tf.math.mod(optimizer.iterations,100) == 0:\n",
    "            printbar()\n",
    "            tf.print('Step = ',optimizer.iterations)\n",
    "            tf.print(\"x = \",x)\n",
    "            tf.print(\"\")\n",
    "\n",
    "    y = a * tf.pow(x,2) + b *x +c\n",
    "    return y\n",
    "\n",
    "tf.print(\"y = \",minimizef())\n",
    "tf.print(\"x = \",x)\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch =  1000\r\n",
      "y =  0\r\n",
      "x =  0.999998569\r\n"
     ]
    }
   ],
   "source": [
    "# 求f(x) = a*x**2 + b*x + c的最小值\n",
    "\n",
    "# 使用optimizer.minimize\n",
    "x = tf.Variable(0.0,name='x',dtype=tf.float32)\n",
    "optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)\n",
    "\n",
    "def f():\n",
    "    a = tf.constant(1.0)\n",
    "    b = tf.constant(-2.0)\n",
    "    c = tf.constant(1.0)\n",
    "    y = a * tf.pow(x,2) + b *x +c\n",
    "    return  y\n",
    "\n",
    "@tf.function\n",
    "def train(epoch = 1000):\n",
    "    for _ in tf.range(epoch):\n",
    "        optimizer.minimize(f,[x])\n",
    "    tf.print(\"epoch = \",optimizer.iterations)\n",
    "    return f()\n",
    "\n",
    "train(1000)\n",
    "tf.print(\"y = \",f())\n",
    "tf.print('x = ',x)\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"fake_model\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "Total params: 1\n",
      "Trainable params: 1\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "Epoch 1/10\n",
      "100/100 [==============================] - 0s 810us/step - loss: 0.2481\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 2/10\n",
      "100/100 [==============================] - 0s 770us/step - loss: 0.0044\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 3/10\n",
      "100/100 [==============================] - 0s 850us/step - loss: 7.6740e-05\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 4/10\n",
      "100/100 [==============================] - 0s 765us/step - loss: 1.3500e-06\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 5/10\n",
      "100/100 [==============================] - 0s 680us/step - loss: 1.8477e-08\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 6/10\n",
      "100/100 [==============================] - 0s 780us/step - loss: 0.0000e+00\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 7/10\n",
      "100/100 [==============================] - 0s 610us/step - loss: 0.0000e+00\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 8/10\n",
      "100/100 [==============================] - 0s 610us/step - loss: 0.0000e+00\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 9/10\n",
      "100/100 [==============================] - 0s 760us/step - loss: 0.0000e+00\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "Epoch 10/10\n",
      "100/100 [==============================] - 0s 760us/step - loss: 0.0000e+00\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\n",
      "x =  0.999998569\r\n",
      "loss =  0\r\n"
     ]
    }
   ],
   "source": [
    "# 求f(x) = a*x**2 + b*x + c的最小值\n",
    "# 使用model.fit\n",
    "\n",
    "tf.keras.backend.clear_session()\n",
    "\n",
    "class FakeModel(tf.keras.models.Model):\n",
    "    def __init__(self,a,b,c):\n",
    "        super(FakeModel,self).__init__()\n",
    "        self.a = a\n",
    "        self.b = b\n",
    "        self.c = c\n",
    "\n",
    "    def build(self):\n",
    "        self.x = tf.Variable(0.0,name='x')\n",
    "        self.built = True\n",
    "\n",
    "\n",
    "    def call(self,features):\n",
    "        loss = self.a * (self.x) **2 + self.b * (self.x) + self.c\n",
    "        return tf.ones_like(features) * loss\n",
    "\n",
    "def myloss(y_true,y_pred):\n",
    "    return tf.reduce_mean(y_pred)\n",
    "\n",
    "model  = FakeModel(tf.constant(1.0),tf.constant(-2.0),tf.constant(1.0))\n",
    "\n",
    "model.build()\n",
    "model.summary()\n",
    "\n",
    "model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.01),loss = myloss)\n",
    "history = model.fit(tf.zeros((100,2)),\n",
    "                    tf.ones(100),batch_size=1,epochs=10)\n",
    "tf.print('x = ',model.x)\n",
    "tf.print(\"loss = \",model(tf.constant(0.0)))\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}